package com.zhan.rkforum.service;

import com.zhan.rkforum.bean.Message;
import com.zhan.rkforum.controller.filter.SensitiveFilter;
import com.zhan.rkforum.dao.MessageMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional

public class MessageServiceImpl implements MessageService{

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SensitiveFilter filter;

    @Override
    public List<Message> selectConversationByPage(int userId, int offset, int limit) {
        return messageMapper.selectConversationByPage(userId, offset, limit);
    }

    @Override
    public List<Message> selectLettersByPage(String conversationId, int offset, int limit) {
        return messageMapper.selectLettersByPage(conversationId, offset, limit);
    }

    @Override
    public int selectConversationCount(int userId) {
        return messageMapper.selectConversationCount(userId);
    }

    @Override
    public int selectUnreadMessageCount(int userId, String conversationId) {
        return messageMapper.selectUnreadMessageCount(userId, conversationId);
    }

    @Override
    public int selectLetterCount(String conversationId) {
        return messageMapper.selectLettersCount(conversationId);
    }

    @Override
    public void updateMessagesStatus(List<Integer> ids, int status) {
        if(ObjectUtils.isNotEmpty(ids)){
            messageMapper.updateMessagesStatus(ids, status);
        }
    }

    @Override
    public void addMessage(int fromId, int toId, String content) {
        content = filter.filter(content);
        Message message = new Message();
        message.setFromId(fromId)
                .setToId(toId)
                .setContent(content)
                .setCreateTime(new Date())
                .setStatus(0);
       String conversationId = fromId > toId ? "" + toId + "_" + fromId  : "" + fromId + "_" + toId;
       message.setConversationId(conversationId);
       messageMapper.addMessage(message);
    }

    public void addMessage(Message message){
        messageMapper.addMessage(message);
    }

    @Override
    public Message findNoticeById(int userId, String topic) {
        return messageMapper.findNoticeById(userId, topic);
    }

    @Override
    public int findTopicNoticeCount(int userId, String topic) {
        return messageMapper.findTopicNoticeCount(userId, topic);
    }

    @Override
    public int unReadTopicNoticeCount(int userId, String topic) {
        return messageMapper.unReadTopicNoticeCount(userId,topic);
    }

    @Override
    public List<Message> findMessageList(int userId, String topic, int offset, int limit) {
        return messageMapper.findMessageList(userId, topic, offset, limit);
    }
}
